﻿package com.vtquang.mymaps;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLParseLocation extends DefaultHandler {
	
	double _lon;
	double _lat;
	MyLocation loc;
	List<MyLocation> list;
	StringBuilder sb = null;

	boolean bItem = false;
	boolean bName = false;
	boolean bVic = false;
	boolean bLat = false;
	boolean bLon = false;
	boolean bIcon = false;

	public XMLParseLocation(double lon, double lat) {
		_lon = lon;
		_lat = lat;
		list = new ArrayList<MyLocation>();
		loc = new MyLocation();
	}

	public List<MyLocation> getListLocation() {
		return list;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);

		if (localName.equals("result")) {
			sb = new StringBuilder("");
			bItem = true;
		} else if (localName.equals("name")) {
			sb = new StringBuilder("");
			bName = true;
		} else if (localName.equals("vicinity")) {
			sb = new StringBuilder("");
			bVic = true;
		} else if (localName.equals("lat")) {
			sb = new StringBuilder("");
			bLat = true;
		} else if (localName.equals("lng")) {
			sb = new StringBuilder("");
			bLon = true;
		} else if (localName.equals("icon")) {
			sb = new StringBuilder("");
			bIcon = true;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		if (bIcon || bLat || bLon || bName || bVic) {
			String str = new String(ch, start, length);
			sb.append(str);
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {

		super.endElement(uri, localName, qName);

		if (localName.equals("result")) {
			MyLocation l = new MyLocation(loc); 
			l.set_distance(MainActivity.computingDistance(_lon, _lat, Double.parseDouble(l.get_lng()), Double.parseDouble(l.get_lat())));
			list.add(l);
			bItem = false;
		} else if (localName.equals("name")) {
			loc.set_name(sb.toString());
			bName = false;
		} else if (localName.equals("vicinity")) {
			loc.set_vicinity(sb.toString());
			bVic = false;
		} else if (localName.equals("lat")) {
			loc.set_lat(sb.toString());
			bLat = false;
		} else if (localName.equals("lng")) {
			loc.set_lng(sb.toString());
			bLon = false;
		} else if (localName.equals("icon")) {
			loc.set_strIcon(sb.toString());
			bIcon = false;
		}
	}
}
